<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户界面</title>
    <!--    引入css文件-->
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}" href="../static/layui/css/layui.css" type="text/css">
    <style>
        body {
            width: 94%;
            margin: 0 auto;
        }
        .layui-form-select {
            width: 240px;
            display: inline-block;
        }
        .btn-box {
            background-color: #fff;
            padding-bottom: 10px;
            border: 1px solid #eee;
            border-bottom: 0;
        }
        .add-user {
            margin-left: 10px;
            margin-top: 10px;
        }
        .layui-table-view {
            margin: 0 0 20px;
        }
    </style>
    <!--   引入js文件-->
    <script th:src="@{/jquery.min.js}" src="../static/jquery.min.js" type="text/javascript"></script>
    <script th:src="@{/layui/layui.js}" src="../static/layui/layui.js" type="text/javascript"></script>
</head>
<body>
<!--    编辑删除tool-->
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit" style="color:#fff;">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" style="color:#fff;">删除</a>
</script>
<div class="btn-box">
    <button type="button" class="layui-btn add-user">添加用户</button>  
</div>
<table id="user_table"  lay-filter="user"></table>
<!--            新增表单-->
<div id="add-main" style="display: none;">
    <form class="layui-form" id="add-form" action="">
        <!--                    <div class="layui-form-item">-->
        <!--                        <label class="layui-form-label" style="width: 100px">场站id</label>-->
        <!--                        <div class="layui-input-block">-->
        <!--                            <input type="text" name="id" required style="width: 240px" lay-verify="required" placeholder="请输入场站id" autocomplete="off" class="layui-input" onkeyup="value=value&&Number(value.replace(/^[^\d]+/g,''))" onblur="value=value&&Number(value.replace(/^[^\d]+/g,''))">-->
        <!--                        </div>-->
        <!--                    </div>-->
        <div class="layui-form-item center">
            <label class="layui-form-label" style="width: 100px">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="username" required value="" style="width: 240px" lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" style="width: 100px">密码</label>
            <div class="layui-input-block">
                <input type="password" name="password" required value="" style="width: 240px" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" style="width: 100px">手机号</label>
            <div class="layui-input-block">
                <input type="text" name="phone" required value="" style="width: 240px" lay-verify="required|phone|number" placeholder="请输入手机号" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" style="width: 100px">用户角色</label>
            <div class="layui-input-block">
                <select name="type" lay-verify="required">
                    <option value="">请选择用户角色</option>
                    <option value="admin">管理员</option>
                    <option value="normal">普通用户</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" style="width: 100px">描述</label>
            <div class="layui-input-block">
                <input type="text" name="description" value="" style="width: 240px" placeholder="请输入描述" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="save">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary" id="closeBtn">重置</button>
            </div>
        </div>
    </form>
</div>
<!--            编辑表单-->
<div id="edit-main" style="display: none;">
    <form class="layui-form" id="edit-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 100px">用户ID</label>
            <div class="layui-input-block">
                <input type="text" name="id" required style="width: 240px" lay-verify="required" placeholder="请输入用户id" autocomplete="off" class="layui-input" id="user_id" disabled="">
            </div>
        </div>
        <div class="layui-form-item center">
            <label class="layui-form-label" style="width: 100px">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="username" required value="" style="width: 240px" lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input" id="user_name">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 100px">密码</label>
            <div class="layui-input-block">
                <input type="password" name="password" required style="width: 240px" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input" id="user_password">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 100px">手机号</label>
            <div class="layui-input-block">
                <input type="text" name="phone" required style="width: 240px" lay-verify="required|phone|number" placeholder="请输入手机号" autocomplete="off" class="layui-input" id="user_phone">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 100px">场站类型</label>
            <div class="layui-input-block">
                <select name="type" lay-verify="required"
                        id="user_type" lay-filter="stat_update_select"
                >
                    <option value="">请选择用户角色</option>
                    <option value="admin">管理员</option>
                    <option value="normal">普通用户</option>
                </select>
                <input type="hidden" required style="width: 240px" placeholder="请输入用户角色" autocomplete="off" class="layui-input" id="hidden_user_type">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 100px">描述</label>
            <div class="layui-input-block">
                <input type="text" name="description" style="width: 240px" placeholder="请输入描述" autocomplete="off" class="layui-input" id="user_description">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="save2">立即提交</button>
            </div>
        </div>
    </form>
</div>
</body>
<script th:inline="javascript">
    let userData = [[${result.data}]]


    layui.use('table', function () {
        let table = layui.table;

        // 渲染用户列表
        table.render({
            elem: '#user_table'
            ,limit: 9999
            ,data: userData || []
            ,cols: [
                [
                    {field: 'id', title: 'id', width: 120, align: 'center'}
                    ,{field: 'username', title: '用户名', minWidth:160, align: 'center'}
                    ,{field: 'password', title: '密码', minWidth:200, align: 'center'}
                    ,{field: 'phone', title: '手机号', minWidth:160, align: 'center'}
                    ,{field: 'type', title: '用户角色', width:140, templet: typeFormat, align: 'center'}
                    ,{field: 'description', title: '描述', minWidth:160, align: 'center'}
                    ,{ fixed: 'right', title: '操作', minWidth: 180, align: 'center', toolbar: '#barDemo' }
                ]
            ]
        })

        //监听工具条
        table.on('tool(user)', function (obj) {
            let data = obj.data;
            if (obj.event === 'detail') {
                layer.msg('ID：' + data.id + ' 的查看操作'); // 暂时不增加查看管理员功能
            }
            else if (obj.event === 'del') {
                layer.confirm('确定要删除用户（'+ data.username +'）么', function (index) {
                    $.ajax({
                        type: "GET",
                        url: '/user/delete',
                        contentType:'application/json',
                        // data: JSON.stringify({ id: data.id }),
                        data: {id:data.id},
                        success: function (res) {
                            if (res.code != 0) {
                                layer.alert(res.msg)
                            } else {
                                layer.alert('删除成功')
                                // layer.alert(res.msg)
                                obj.del();
                                layer.close(index);
                                // 删除场站后，与之相关的对应关系也要删除，所以刷新整个页面
                                parent.location.reload();
                            }
                        }
                    })
                });
            } else if (obj.event === 'edit') {
                let opts = document.getElementsByTagName('option')
                // layer.alert('编辑行：<br>' + JSON.stringify(data.name))
                $("#user_id").val(data.id);
                $("#user_name").val(data.username);
                $("#user_password").val(data.password);
                $("#hidden_user_type").val(data.type );
                $("#user_phone").val(data.phone );
                $("#user_description").val(data.description);
                setType() // 加载类型

                layer.open({
                    type: 1, skin: 'layui-layer-rim', //加上边框
                    area: ['450px', '450px'], //宽高
                    // offset: height + 'px',
                    content: $("#edit-main"),
                    title: ['编辑用户信息','margin-bottom:15px'],
                    success:function (layero, index){
                        // success成功后执行的回调
                        // yes 点击确认后执行的回调 但是这里由于是表单，监听的submit事件
                    }
                });
            }
        });
    });

    //  新增事件
    $('.add-user').on('click', function () {
        let type = $(this).data('type'); //页面层
        layer.open({
            type: 1, skin: 'layui-layer-rim', //加上边框
            area: ['430px', '400px'], //宽高
            content: $("#add-main"),
            title: ['新增用户','margin-bottom:15px']
        });
    });

    // 注册弹层的表格
    layui.use(['layer', 'form'], function () {
        let layer = layui.layer, $ = layui.jquery, form = layui.form;

        //提交监听事件
        form.on('submit(save)', function (data) {
            params = data.field;
            submit($, params);
            return false;
        })
        //修改时提交监听事件
        form.on('submit(save2)', function (data) {
            params = data.field;
            submit2($, params);
            return false;
        })

        // 更新的select事件
        form.on('select(stat_update_select)', function (data) {
            // console.log(data)
            // console.log(data.value)
        })


    })

    //增加提交
    function submit ($, params) {
        $.ajax({
            type: "post",
            url: '/user/add',
            data: JSON.stringify(params),
            contentType:'application/json',
            success: function (res) {
                if (res.code != 0) {
                    layer.alert(res.msg)
                } else {
                    layer.msg(res.msg, { icon: 0, time: 500 },
                        function () {
                            parent.location.reload();
                            // 页面刷新
                            return false
                        })
                }
            }
        });
    }
    //修改提交
    function submit2 ($, params) {
        $.ajax({
            type: "POST",
            url: '/user/update',
            data: JSON.stringify(params),
            contentType:'application/json',
            success: function (res) {
                if (res.code != 0) {
                    layer.alert(res.msg)
                } else {
                    layer.msg(res.msg,
                        { icon: 0, time: 500 },
                        function () {
                            parent.location.reload();
                            // 页面刷新
                            return false
                        })
                }
            }
        });
    }

    // 类型格式化
    function typeFormat(d) {
        let str
        if(d.type == 'admin') {
            str = '管理员'
        } else if(d.type == 'normal') {
            str = '普通用户'
        } else {
            str = d.type || ''
        }
        return str
    }

    //数据回显
    function setType (value) {
        $('#user_type').html(`
                    <option value="">请选择用户角色</option>
                    <option value="admin">管理员</option>
                    <option value="normal">普通用户</option>
        `)
        $('#user_type').each(function (){
            let hiddenType = $('#hidden_user_type').val()

            $(this).children("option").each(function (i,n) {
                if(this.value == hiddenType) {
                    $(this).attr("selected", "selected")
                }
            })
            layui.form.render('select');
        })
    }

</script>
</html>